__author__ = 'chzhu'

from Configuration import Config
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import *
import sqlalchemy
from sqlalchemy.orm import sessionmaker
Base = declarative_base()

class Database(object):

    dbo = None

    def __new__(cls, *args, **kwargs):
        if not cls.dbo:
            cls.dbo = super(Database, cls).__new__(cls, *args, **kwargs)
            cls.dbo.engine_info = 'mysql+pymysql://' + Config.user + ':' + Config.passwd + '@' + Config.host + '/' + Config.database + '?charset=' + Config.charset
            cls.dbo.engine = sqlalchemy.create_engine(cls.dbo.engine_info)
        return cls.dbo


    def connect(self):
        self.connection = self.engine.connect()
        Session = sessionmaker(bind=self.engine, autocommit=True)
        self.session = Session()

    def close(self):
        self.session.close()
        self.connection.close()

Database()

class Mobile(Base):
    __table__ = Table(Config.tables['mobile'], Base.metadata, autoload=True, autoload_with=Database.dbo.engine)

    def __init__(self, l):
        for key, value in l.items():
            setattr(self, key, value)